<!--
 * @Author: susu 1628469970@qq.com
 * @Date: 2023-09-05 15:24:07
 * @LastEditors: susu 1628469970@qq.com
 * @LastEditTime: 2023-09-05 15:26:12
 * @FilePath: \SUSU_CSS\web\canvas\3.dd.htm
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>

    // 创建一个粒子对象
    function Particle ( x, y, radius ) {
        this.x = x;
        this.y = y;
        this.radius = radius;
    }

    // 在Canvas中绘制粒子
    Particle.prototype.draw = function ( ctx ) {
        ctx.beginPath();
        ctx.arc( this.x, this.y, this.radius, 0, Math.PI * 2 );
        ctx.fillStyle = 'red';
        ctx.fill();
        ctx.closePath();
    };

    // 检测两个粒子是否发生碰撞
    function checkCollision ( particle1, particle2 ) {
        var dx = particle1.x - particle2.x;
        var dy = particle1.y - particle2.y;
        var distance = Math.sqrt( dx * dx + dy * dy );

        return distance < particle1.radius + particle2.radius;
    }

    // 创建Canvas元素并获取上下文
    var canvas = document.createElement( 'canvas' );
    document.body.appendChild( canvas );
    var ctx = canvas.getContext( '2d' );

    // 定义粒子数组
    var particles = [];

    // 创建粒子并添加到数组中
    for ( var i = 0; i < 100; i++ ) {
        var x = Math.random() * canvas.width;
        var y = Math.random() * canvas.height;
        var radius = Math.random() * 10 + 5;

        var particle = new Particle( x, y, radius );
        particles.push( particle );
    }

    // 绘制粒子并进行碰撞检测
    function draw () {
        ctx.clearRect( 0, 0, canvas.width, canvas.height );

        for ( var i = 0; i < particles.length; i++ ) {
            var particle = particles[i];
            particle.draw( ctx );

            for ( var j = i + 1; j < particles.length; j++ ) {
                var otherParticle = particles[j];

                if ( checkCollision( particle, otherParticle ) ) {
                    // 处理碰撞逻辑
                    // 例如，改变粒子的颜色或位置
                    particle.x = Math.random() * canvas.width;
                    particle.y = Math.random() * canvas.height;
                    otherParticle.x = Math.random() * canvas.width;
                    otherParticle.y = Math.random() * canvas.height;
                }
            }
        }

        requestAnimationFrame( draw );
    }

    // 开始绘制
    draw();
</script>

</html>